package models

import (
	"tms-server/driver"
)

const (
	DBAttachment       = "attachment"
	DBCinf             = "cinf"
	DBDep              = "dep"
	DBDispatch         = "dispatch"
	DBEmployee         = "employee"
	DBOrder1           = "order1"
	DBOrdr             = "ordr"
	DBPartner          = "partner"
	DBPwd              = "pwd"
	DBTruck            = "truck"
	DBTruckhead        = "truckhead"
	DBTrucktail        = "trucktail"
	DBUser             = "user"
	DBAuthority        = "authority"
	DBRole             = "role"
	DBRelRoleAuthority = "rel_role_authority"
	DBRelDepRole       = "rel_dep_role"
)

var TablesMap = map[string]interface{}{
	DBAttachment:       &Attachment{},
	DBCinf:             &Cinf{},
	DBDep:              &Dep{},
	DBDispatch:         &Dispatch{},
	DBEmployee:         &Employee{},
	DBOrder1:           &Order1{},
	DBOrdr:             &Ordr{},
	DBPartner:          &Partner{},
	DBPwd:              &Pwd{},
	DBTruck:            &Truck{},
	DBTruckhead:        &Truckhead{},
	DBTrucktail:        &Trucktail{},
	DBUser:             &User{},
	DBAuthority:        &Authority{},
	DBRole:             &Role{},
	DBRelRoleAuthority: &RelRoleAuthority{},
	DBRelDepRole:       &RelDepRole{},
}

func Sync() (err error) {
	syncTables := make([]interface{}, 0)
	for _, tableStruct := range TablesMap {
		syncTables = append(syncTables, tableStruct)
	}
	err = driver.X.Sync2(syncTables...)
	if err != nil {
		return
	}

	for tableName, tableStruct := range TablesMap {
		var exist bool
		exist, err = driver.X.IsTableExist(tableName)
		if err != nil {
			return
		}
		if !exist {
			err = driver.X.CreateTables(tableStruct)
			if err != nil {
				return
			}
		}
	}

	return
}
